package com.zsj.comminlibrary.util;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import java.util.List;


public class NetworkUtil {

    public static boolean hasNetwork(Context context) {
        if (context == null)
            return false;
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (null == activeNetInfo || !activeNetInfo.isConnected()) {
            return false;
        }
        return true;
    }

    public static boolean isWifiConnection(Context context) {
        ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectMgr.getActiveNetworkInfo();

        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean isNetConnection(Context context) {
        ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectMgr.getActiveNetworkInfo();

        return info != null && info.getType() == ConnectivityManager.TYPE_MOBILE;
    }

    public static boolean isWifiEncrypted(String ssid, WifiManager wifiManager) {
        List<ScanResult> scanResults = wifiManager.getScanResults();
        String capability = "";
        if (scanResults != null && !scanResults.isEmpty()) {
            for (ScanResult result : scanResults) {
                if (result.SSID.equals(ssid)) {
                    capability = result.capabilities;
                    break;
                }
            }
        }
        if (capability.contains("WEP")) {
            return true;
        } else if (capability.contains("PSK")) {
            return true;
        } else if (capability.contains("EAP")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否打开gps
     * @param context
     * @return
     */
    public static boolean isOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
}

